package java6703.nio2;

import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.stream.Stream;

public class NIO2Dir6703Controller {

    @FXML
    private TextField tfDir;

    @FXML
    private Label lblCount;

    @FXML
    private TableView<?> tableFiles;

    @FXML
    private TableColumn<?, ?> colName;

    @FXML
    private TableColumn<?, ?> colTime;

    @FXML
    private TableColumn<?, ?> colType;

    @FXML
    private TableColumn<?, ?> colSize;

    private ObservableList<MyFile6703> list;
    //当前目录，用于
    //（1）双击进入下一级日录时生成新的当前日录
    //（2）双击..返国上一级胃录时，生成新的当前日录
    //不能用绑定，因为双向都需要单独修改
    private Path currentDir;
    //统计子目录和文件数
    private int nDir = 0, nFile = 0;

    @FXML
    private void initialize() {
        colName.setCellValueFactory(new PropertyValueFactory<>("name"));
        colType.setCellValueFactory(new PropertyValueFactory<>("type"));
        colTime.setCellValueFactory(new PropertyValueFactory<>("modifiedTime"));
        colSize.setCellValueFactory(new PropertyValueFactory<>("size"));
        list = (ObservableList<MyFile6703>) tableFiles.getItems();
    }

    @FXML
    void doubleClick(MouseEvent event) throws IOException {
        if (event.getClickCount() == 2) {
            //鼠标双击
            //读取选中项
            MyFile6703 file = (MyFile6703) tableFiles.getSelectionModel().getSelectedItem();
            if (file == null) return;//在标题上双击
            if ("文件夹".equals(file.getType())) {
                //根据当前选项，定义要进入的下一级目录
                Path newDir = currentDir.resolve(file.getName());
                setCurrentDir(newDir);//修改当前目录
            } else if ("..".equals(file.getName())) {
                //正确地从当前目录中读收上一级目录
                Path newDir = currentDir.toRealPath().getParent();
                setCurrentDir(newDir);//修改当前目录
            }
        }
    }

    @FXML
    void listAll(ActionEvent event) {
        //检查输入的路径是否正确
        String inputDir = tfDir.getText().trim();
        if (inputDir.isEmpty()) {
            inputDir = ".";
        } else {
            if (!Files.isDirectory(Paths.get(inputDir))) {
                lblCount.setText("不是目录!! ");
                return;
            } else if (inputDir.matches("[a-zA-Z]:")) {
                inputDir += ".";
            }

        }
        setCurrentDir(Paths.get(inputDir));
    }

    private void setCurrentDir(Path dir) {
        currentDir = dir;
        tfDir.setText(dir.toString());//在文本框中显示当前目录
        nDir = 0;
        nFile = 0;
        list.clear();
        try (Stream<Path> pathStream = Files.list(dir)) {
            //当前目录的内容添加到Tableview
            pathStream.forEach(this::addList);
        } catch (IOException e) {
            list.clear();
            e.printStackTrace();
            lblCount.setText(e.getMessage());
            return;
        }
        lblCount.setText("子目录:" + nDir + "，文件:" + nFile);
        //排序
        tableFiles.getSortOrder().clear();
        tableFiles.getSortOrder().addAll();
        colType.setSortType(TableColumn.SortType.DESCENDING);
        colName.setSortType(TableColumn.SortType.ASCENDING);
        if (!isRoot(currentDir)){
            //当前目录不是根目录,第一行显示..，用于返网上一级目录
            MyFile6703 parent = new MyFile6703();
            parent.setName("..");
            list.add(0, parent);
        }

    }

    private boolean isRoot(Path path) {
        //转为绝对路径后判断是否根目录
        if(!path.isAbsolute()){
            path=path.toAbsolutePath();
        }//没有父目录，说明已是根目录
        return path.getParent()==null;
    }

    private void addList(Path path) {
        MyFile6703 file = new MyFile6703();
        file.setName(path.getFileName().toString());
        BasicFileAttributes attributes = null;
        try {
            attributes = Files.readAttributes(path,BasicFileAttributes.class);
            //NI02的文件修改时同是FileTime，倍助Instant转观LocalDateTime
            LocalDateTime time = attributes.lastModifiedTime().toInstant()
                    .atZone(ZoneId.systemDefault()).toLocalDateTime();
            String strTime = time.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM));
            file.setModifiedTime(strTime);
            if (Files.isDirectory(path)){
                file.setSize("");
                file.setType("文件夹");
                nDir++;
            }else {
                nFile++;
                file.setSize((attributes.size()/ 1024+1)+"KB");
                file.setType("");
            }
            list.add(file);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

